#include "fsxwsmainwindow.h"
#include "ui_fsxwsmainwindow.h"
using namespace FsxWsGUI;

//
// Save as JSON file
//
void FsxWsMainWindow::saveJsonDataAsFile(const QString &filename) {
    // entry check
    if (filename.length()<1 || !FsxWsMainWindow::_fsxSimConnect) {
        FsxWsMainWindow::slotLogMessage("No filename or FSX not connect, file not saved", QtDebugMsg);
    } else {
        QString json = emit FsxWsMainWindow::signalFSXAircraftsJsonData(JsonParameter(-1, true, -1));
        if (json.length() < 1) {
            FsxWsMainWindow::slotLogMessage("No JSON data, file not saved", QtDebugMsg);
            FsxWsMainWindow::slotSetConsoleTab();
        } else {
            FsxWsMainWindow::saveQStringToFile(filename, json);
        }
    }
}

//
// Save as KML file (Google Earth)
//
void FsxWsMainWindow::saveWaypointsAsKml(const QString &filename, qint64 resolutionMs) {
    // entry check
    if (filename.length()<1 || !FsxWsMainWindow::_fsxSimConnect || !FsxWsMainWindow::_lastSelectedAircraft.isValid()) {
        FsxWsMainWindow::slotLogMessage("No filename, FSX not connect, or not aircraft selected. File not saved", QtDebugMsg);
        FsxWsMainWindow::slotSetConsoleTab();
        return;
    }
    if (!FsxWsMainWindow::_fsxWsSettings) {
        FsxWsMainWindow::slotLogMessage("No settings, " + filename + " not saved", QtWarningMsg);
        FsxWsMainWindow::slotSetConsoleTab();
        return;
    }

    // act on last selected aircraft
    KmlParameter parameter(-1, FsxWsMainWindow::_fsxWsSettings->getKmlWaypointModelPathOrUrl(), resolutionMs);
    QString kml = FsxWsMainWindow::_lastSelectedAircraft.toKml(0, parameter);
    if (kml.length() < 1) {
        FsxWsMainWindow::slotLogMessage("No KML data, file " + filename + " not saved", QtDebugMsg);
        FsxWsMainWindow::slotSetConsoleTab();
    } else {
        FsxWsMainWindow::saveQStringToFile(filename, kml);
    }
}

//
// Save a QString into a file (e.g. JSON, KML)
//
void FsxWsMainWindow::saveQStringToFile(const QString &filename, const QString &content) {
    if (filename.length() < 1) return;
    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::information(this, tr("Unable to open file"), file.errorString());
        FsxWsMainWindow::slotLogMessage(QString("Unable to open file %1, %2").arg(filename).arg(file.errorString()), QtWarningMsg);
        FsxWsMainWindow::slotSetConsoleTab();
    } else {
        QTextStream fileStream(&file);
        fileStream << content;
        file.close();
        FsxWsMainWindow::slotLogMessage(QString("File %1 saved").arg(filename), QtDebugMsg);
    }
}
